package com.example.demo.interceptorToken;

import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author hulei
 * @date 2024/1/11 19:48
 * @Description 由于 request中getReader()和getInputStream()只能调用一次 导致在Controller @ResponseBody的时候获取不到 null 或 Stream closed
 * 在项目中，可能会出现需要针对接口参数进行校验等问题
 * 构建可重复读取inputStream的request
 */
public class RequestWrapper extends HttpServletRequestWrapper {
    // 将流保存下来
    private final byte[] requestBody;

    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        requestBody = readBytes(request.getReader());
    }

    @Override
    public ServletInputStream getInputStream() {

        final ByteArrayInputStream basic = new ByteArrayInputStream((requestBody != null && requestBody.length >0) ? requestBody : new byte[]{});

        return new ServletInputStream() {

            @Override
            public int read() {
                return basic.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    /**
     * 通过BufferedReader和字符编码集转换成byte数组
     */
    private byte[] readBytes(BufferedReader br) throws IOException {
        String str;
        StringBuilder retStr = new StringBuilder();
        while ((str = br.readLine()) != null) {
            retStr.append(str);
        }
        if (StringUtils.isNotBlank(retStr.toString())) {
            return retStr.toString().getBytes(StandardCharsets.UTF_8);
        }
        return null;
    }
}